import express from 'express';
import cors from 'cors';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import userRoutes from './routes/authRoutes';
import voteRoutes from './routes/voteRoutes';
import uploadRoutes from './routes/uploadRoutes';

// 加载环境变量
dotenv.config();

const app = express();

// 配置 CORS，允许前端跨域访问
app.use(cors({
  origin: 'http://localhost:3000', // 前端地址
  credentials: true
}));
// 解析 JSON 请求体
app.use(express.json());
// 静态托管上传资源
app.use('/uploads', express.static('uploads'));
// 挂载用户、投票、上传相关路由
app.use('/api/user', userRoutes);
app.use('/api/vote', voteRoutes);
app.use(uploadRoutes);

const PORT = process.env.PORT || 5000;
const MONGO_URI = process.env.MONGO_URI || 'mongodb://localhost:27017/blockchain-voting';

// 连接 MongoDB，成功后启动服务
mongoose.connect(MONGO_URI)
  .then(() => {
    app.listen(PORT, () => {
      console.log(`Server running on port ${PORT}`);
      // 打印合约工厂地址（如有）
      if (process.env.VOTING_FACTORY_ADDRESS) {
        console.log('VOTING_FACTORY_ADDRESS:', process.env.VOTING_FACTORY_ADDRESS);
      }
    });
  })
  .catch((err) => {
    console.error('MongoDB connection error:', err);
  });